import 'package:flutter/material.dart';
import 'package:flutter_xupdate/flutter_xupdate.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:path_provider/path_provider.dart';

class UpdateManager {
  static var isplatformAndriod = false;
  // 检查更新并显示对话框
  static Future<void> checkAndShowUpdate(BuildContext context) async {
    try {
      // 从服务器获取版本信息
      final response = await http.get(Uri.parse('https://ljwl.tech/app/version'));
      XLogger.error(response.statusCode);
      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        final serverVersion = data['data']['version'] as String;
        final downloadUrl = data['data']['url'] as String;
        XLogger.error(serverVersion);

        // 获取本地应用版本
        final packageInfo = await PackageInfo.fromPlatform();
        final localVersion = packageInfo.version;

        XLogger.error(_isVersionOlder(localVersion, serverVersion));
        XLogger.info(_isVersionOlder(localVersion, serverVersion));
        XLogger.info(localVersion);

        // 检查是否需要更新
        if (_isVersionOlder(localVersion, serverVersion)) {
          XLogger.error("立即更新");
          _showUpdateDialog(context, serverVersion, downloadUrl);
        }
      }
    } catch (e) {
      print('检查更新失败: $e');
    }
  }

  // 显示更新对话框
  static void _showUpdateDialog(BuildContext context, String newVersion, String downloadUrl) {
    showDialog(
      context: context,
      barrierDismissible: false, // 点击外部不可关闭
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('发现新版本'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('新版本 $newVersion 已可用'),
              const SizedBox(height: 12),
              Text('请更新到最新版本'),
            ],
          ),
          actions: [
            TextButton(
              child: const Text('立即更新'),
              onPressed: () async {
                await _openAppStore(context,newVersion,downloadUrl);
              },
            ),
          ],
        );
      },
    );
  }

  // 打开应用商店
  static Future<void> _openAppStore(BuildContext context,String versionName, String downloadUrl) async {
    try {
      final packageInfo = await PackageInfo.fromPlatform();
      final appId = packageInfo.packageName;

      if (Theme.of(context).platform == TargetPlatform.android) {
        final updateEntity = UpdateEntity(
          hasUpdate: true,
          versionCode: -1,
          versionName: versionName,
          updateContent: "",
          downloadUrl: downloadUrl,
          isForce: true,
        );

        FlutterXUpdate.updateByInfo(
          updateEntity: updateEntity,
          themeColor: '#3B82F6', // 进度条颜色
        );

      } else if (Theme.of(context).platform == TargetPlatform.iOS) {
        // iOS直接跳转App Store
        print('iOS直接跳转App Store');

        final url = 'https://itunes.apple.com/cn/app/id6741039198?mt=8';
        launchUrl(Uri.parse(url));

        // await launchUrl(Uri.parse(url), mode: LaunchMode.externalApplication);
      }
    } catch (e) {
      print('打开应用商店失败: $e');
      // 显示错误提示
      ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('无法自动跳转到应用商店，请手动更新'))
      );
    }
  }

  // 版本号比较
  static bool _isVersionOlder(String current, String target) {
    final currentParts = current.split('.').map(int.parse).toList();
    final targetParts = target.split('.').map(int.parse).toList();

    // 补全版本号到三位
    while (currentParts.length < 3) currentParts.add(0);
    while (targetParts.length < 3) targetParts.add(0);

    for (int i = 0; i < 3; i++) {
      if (currentParts[i] < targetParts[i]) return true;
      if (currentParts[i] > targetParts[i]) return false;
    }
    return false;
  }


}